<template>
  <div class="admin-statistics-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">数据统计</h1>
      <p class="page-subtitle">平台运营数据分析与统计报表</p>
    </div>

    <!-- 时间筛选 -->
    <div class="filter-section">
      <el-card>
        <div class="filter-controls">
          <div class="date-range">
            <span class="filter-label">时间范围：</span>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              unlink-panels
              :default-time="['00:00:00', '23:59:59']"
              @change="handleDateRangeChange"
            />
          </div>
          <div class="quick-filters">
            <span class="filter-label">快速筛选：</span>
            <el-button
              v-for="filter in quickFilters"
              :key="filter.value"
              type="text"
              :class="{ 'text-primary': selectedQuickFilter === filter.value }"
              @click="handleQuickFilterClick(filter)"
            >
              {{ filter.label }}
            </el-button>
          </div>
          <div class="export-btn">
            <el-button type="primary" @click="exportStatistics">
              <el-icon><Download /></el-icon>
              导出报表
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 核心指标 -->
    <div class="key-metrics">
      <el-card class="metric-card">
        <div class="metric-content">
          <span class="metric-number">{{ totalUsers }}</span>
          <span class="metric-label">总用户数</span>
        </div>
        <div class="metric-trend">
          <span class="trend-value" :class="userTrend > 0 ? 'positive' : 'negative'">
            {{ userTrend > 0 ? '+' : '' }}{{ userTrend }}%
          </span>
          <span class="trend-label">较上期</span>
        </div>
        <el-icon class="metric-icon"><User /></el-icon>
      </el-card>
      <el-card class="metric-card">
        <div class="metric-content">
          <span class="metric-number">{{ activeUsers }}</span>
          <span class="metric-label">活跃用户</span>
        </div>
        <div class="metric-trend">
          <span class="trend-value" :class="activeUserTrend > 0 ? 'positive' : 'negative'">
            {{ activeUserTrend > 0 ? '+' : '' }}{{ activeUserTrend }}%
          </span>
          <span class="trend-label">较上期</span>
        </div>
        <el-icon class="metric-icon"><View /></el-icon>
      </el-card>
      <el-card class="metric-card">
        <div class="metric-content">
          <span class="metric-number">{{ totalPosts }}</span>
          <span class="metric-label">总帖子数</span>
        </div>
        <div class="metric-trend">
          <span class="trend-value" :class="postTrend > 0 ? 'positive' : 'negative'">
            {{ postTrend > 0 ? '+' : '' }}{{ postTrend }}%
          </span>
          <span class="trend-label">较上期</span>
        </div>
        <el-icon class="metric-icon"><Message /></el-icon>
      </el-card>
      <el-card class="metric-card">
        <div class="metric-content">
          <span class="metric-number">{{ totalQuestions }}</span>
          <span class="metric-label">总题目数</span>
        </div>
        <div class="metric-trend">
          <span class="trend-value" :class="questionTrend > 0 ? 'positive' : 'negative'">
            {{ questionTrend > 0 ? '+' : '' }}{{ questionTrend }}%
          </span>
          <span class="trend-label">较上期</span>
        </div>
        <el-icon class="metric-icon"><Document /></el-icon>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>用户增长趋势</span>
            <el-select v-model="userChartType" placeholder="图表类型" class="chart-type-select">
              <el-option label="折线图" value="line" />
              <el-option label="柱状图" value="bar" />
            </el-select>
          </div>
        </template>
        <div class="chart-container">
          <canvas ref="userGrowthChart" width="400" height="200"></canvas>
        </div>
      </el-card>
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>内容活跃度分析</span>
            <el-select v-model="contentType" placeholder="内容类型" class="chart-type-select">
              <el-option label="帖子" value="posts" />
              <el-option label="评论" value="comments" />
              <el-option label="题目" value="questions" />
            </el-select>
          </div>
        </template>
        <div class="chart-container">
          <canvas ref="contentActivityChart" width="400" height="200"></canvas>
        </div>
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <div class="data-tables">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>用户活跃度排行</span>
            <el-select v-model="activeSortType" placeholder="排序方式" class="chart-type-select">
              <el-option label="发帖数" value="posts" />
              <el-option label="评论数" value="comments" />
              <el-option label="做题数" value="questions" />
            </el-select>
          </div>
        </template>
        <el-table :data="userRankingData" style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80" align="center" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="posts" label="发帖数" width="120" align="center" />
          <el-table-column prop="comments" label="评论数" width="120" align="center" />
          <el-table-column prop="questions" label="做题数" width="120" align="center" />
          <el-table-column prop="loginTime" label="最后登录" width="180" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                {{ scope.row.status === 'active' ? '活跃' : '普通' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, User, View, Message, Document } from '@element-plus/icons-vue';
import { Chart } from 'chart.js';

// 日期范围
const dateRange = ref<[Date, Date] | null>(null);
const selectedQuickFilter = ref('');

// 图表类型
const userChartType = ref<'line' | 'bar'>('line');
const contentType = ref('posts');
const activeSortType = ref('posts');

// 核心指标数据
const totalUsers = ref(12548);
const activeUsers = ref(8926);
const totalPosts = ref(28652);
const totalQuestions = ref(15820);

// 趋势数据
const userTrend = ref(12.5);
const activeUserTrend = ref(8.3);
const postTrend = ref(15.2);
const questionTrend = ref(9.1);

// 快速筛选选项
const quickFilters = ref([
  { label: '近7天', value: '7d' },
  { label: '近30天', value: '30d' },
  { label: '近90天', value: '90d' },
  { label: '近12个月', value: '12m' },
  { label: '本年度', value: 'year' },
  { label: '上年度', value: 'lastYear' }
]);

// 用户排名数据
const userRankingData = ref([
  { rank: 1, username: '行测大神', posts: 128, comments: 356, questions: 892, loginTime: '2024-05-10 09:23', status: 'active' },
  { rank: 2, username: '申论小王子', posts: 112, comments: 289, questions: 765, loginTime: '2024-05-10 10:15', status: 'active' },
  { rank: 3, username: '公考考霸', posts: 98, comments: 324, questions: 912, loginTime: '2024-05-10 08:45', status: 'active' },
  { rank: 4, username: '面试达人', posts: 87, comments: 256, questions: 654, loginTime: '2024-05-09 16:30', status: 'active' },
  { rank: 5, username: '公基小王子', posts: 76, comments: 198, questions: 789, loginTime: '2024-05-09 14:20', status: 'active' },
  { rank: 6, username: '资料分析大师', posts: 65, comments: 213, questions: 845, loginTime: '2024-05-08 11:05', status: 'active' },
  { rank: 7, username: '判断推理高手', posts: 54, comments: 176, questions: 792, loginTime: '2024-05-08 09:30', status: 'active' },
  { rank: 8, username: '言语理解专家', posts: 45, comments: 156, questions: 687, loginTime: '2024-05-07 15:45', status: 'active' },
  { rank: 9, username: '常识判断王者', posts: 38, comments: 142, questions: 754, loginTime: '2024-05-07 11:20', status: 'normal' },
  { rank: 10, username: '面试准备中', posts: 32, comments: 128, questions: 654, loginTime: '2024-05-06 16:10', status: 'normal' }
]);

// 图表引用
const userGrowthChart = ref<HTMLCanvasElement | null>(null);
const contentActivityChart = ref<HTMLCanvasElement | null>(null);

// 图表实例
let userGrowthChartInstance: Chart | null = null;
let contentActivityChartInstance: Chart | null = null;

// 处理日期范围变化
const handleDateRangeChange = () => {
  selectedQuickFilter.value = '';
  // 重新加载数据
  loadStatisticsData();
};

// 处理快速筛选点击
const handleQuickFilterClick = (filter: any) => {
  selectedQuickFilter.value = filter.value;
  // 设置日期范围
  const now = new Date();
  let startDate = new Date();
  
  switch (filter.value) {
    case '7d':
      startDate.setDate(now.getDate() - 7);
      break;
    case '30d':
      startDate.setDate(now.getDate() - 30);
      break;
    case '90d':
      startDate.setDate(now.getDate() - 90);
      break;
    case '12m':
      startDate.setMonth(now.getMonth() - 12);
      break;
    case 'year':
      startDate = new Date(now.getFullYear(), 0, 1);
      break;
    case 'lastYear':
      startDate = new Date(now.getFullYear() - 1, 0, 1);
      now.setDate(now.getDate() - 365);
      break;
  }
  
  dateRange.value = [startDate, now];
  // 重新加载数据
  loadStatisticsData();
};

// 加载统计数据
const loadStatisticsData = () => {
  // 模拟数据加载
  ElMessage.info('数据加载中...');
  
  // 这里应该是实际的数据请求逻辑
  setTimeout(() => {
    ElMessage.success('数据加载完成');
    // 更新图表
    initCharts();
  }, 800);
};

// 初始化所有图表
const initCharts = () => {
  initUserGrowthChart();
  initContentActivityChart();
};

// 初始化用户增长图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return;
  
  const ctx = userGrowthChart.value.getContext('2d');
  if (!ctx) return;
  
  // 销毁已存在的图表
  if (userGrowthChartInstance) {
    userGrowthChartInstance.destroy();
  }
  
  // 生成模拟数据
  const labels: string[] = [];
  const data = [];
  const now = new Date();
  
  // 根据当前选择的日期范围生成对应的数据
  let days = 30;
  if (selectedQuickFilter.value === '7d') days = 7;
  if (selectedQuickFilter.value === '90d') days = 90;
  if (selectedQuickFilter.value === '12m') {
    // 12个月的数据
    for (let i = 11; i >= 0; i--) {
      const date = new Date(now);
      date.setMonth(date.getMonth() - i);
      labels.push(`${date.getFullYear()}/${date.getMonth() + 1}`);
      data.push(10000 + Math.floor(Math.random() * 2000) + i * 500);
    }
  } else {
    // 按天的数据
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      labels.push(`${date.getMonth() + 1}/${date.getDate()}`);
      data.push(10000 + Math.floor(Math.random() * 2000));
    }
  }
  
  userGrowthChartInstance = new Chart(ctx, {
    type: userChartType.value, // 折线图或柱状图
    data: {
      labels,
      datasets: [{
        label: '用户数量',
        data,
        borderColor: '#409eff',
        backgroundColor: userChartType.value === 'line' ? 'rgba(64, 158, 255, 0.1)' : 'rgba(64, 158, 255, 0.8)',
        tension: userChartType.value === 'line' ? 0.3 : 0,
        fill: userChartType.value === 'line',
        borderWidth: 2
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: false,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
};

// 初始化内容活跃度图表
const initContentActivityChart = () => {
  if (!contentActivityChart.value) return;
  
  const ctx = contentActivityChart.value.getContext('2d');
  if (!ctx) return;
  
  // 销毁已存在的图表
  if (contentActivityChartInstance) {
    contentActivityChartInstance.destroy();
  }
  
  // 生成模拟数据
  const labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  let data: number[] = [];
  let label = '';
  let color = '';
  
  // 根据内容类型生成不同的数据
  if (contentType.value === 'posts') {
    data = [85, 92, 78, 95, 120, 150, 130];
    label = '帖子数量';
    color = '#67c23a';
  } else if (contentType.value === 'comments') {
    data = [350, 420, 380, 450, 520, 650, 580];
    label = '评论数量';
    color = '#e6a23c';
  } else if (contentType.value === 'questions') {
    data = [280, 320, 290, 350, 420, 380, 410];
    label = '题目练习量';
    color = '#f56c6c';
  }
  
  contentActivityChartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        label,
        data,
        backgroundColor: color,
        borderWidth: 0,
        borderRadius: 4
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  });
};

// 导出统计报表
const exportStatistics = () => {
  ElMessageBox.confirm(
    '确定要导出当前统计报表吗？',
    '确认导出',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.info('报表导出中，请稍候...');
    // 模拟导出过程
    setTimeout(() => {
      ElMessage.success('报表导出成功！');
    }, 1500);
  }).catch(() => {
    ElMessage.info('已取消导出');
  });
};

// 监听图表类型变化
userChartType.value = 'line';
contentType.value = 'posts';

// 生命周期钩子
onMounted(() => {
  // 默认选择近30天
  handleQuickFilterClick(quickFilters.value[1]);
  
  nextTick(() => {
    initCharts();
  });
});
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

.admin-statistics-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: $text-primary;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: $text-secondary;
  margin: 5px 0 0 0;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 15px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quick-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-label {
  font-size: 14px;
  color: $text-regular;
}

.chart-type-select {
  width: 120px;
}

.key-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: $border-radius-base;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.metric-content {
  flex: 1;
}

.metric-number {
  font-size: 28px;
  font-weight: 600;
  color: $text-primary;
  line-height: 1.2;
}

.metric-label {
  font-size: 14px;
  color: $text-secondary;
  margin-top: 5px;
  display: block;
}

.metric-trend {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 20px;
}

.trend-value {
  font-size: 16px;
  font-weight: 600;
}

.trend-value.positive {
  color: $success-color;
}

.trend-value.negative {
  color: $danger-color;
}

.trend-label {
  font-size: 12px;
  color: $text-placeholder;
  margin-top: 2px;
}

.metric-icon {
  font-size: 36px;
  color: $primary-color;
  opacity: 0.1;
  position: absolute;
  right: 20px;
  bottom: 10px;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
}

.chart-card {
  border-radius: $border-radius-base;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.chart-container {
  height: 300px;
  padding: 20px;
}

.data-tables {
  margin-bottom: 30px;
}

// 响应式设计
@media (max-width: 1200px) {
  .key-metrics {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .date-range,
  .quick-filters,
  .export-btn {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .admin-statistics-view {
    padding: 10px;
  }
  
  .key-metrics {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .chart-type-select {
    width: 100%;
  }
}
</style>